<?php


namespace app\common\cachemodel\lucky;


use app\common\model\BaseCache;
use XznsTools\cache\CacheManage;

class AppLuckyDraw extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_lucky_draw';

    protected $cacheModel = 'lucky_planet.draw';

    /**
     * 获取抽奖结果
     * @return mixed|null
     * @throws \Exception
     */
    public function getDrawResult(int $uid)
    {
        $drawList = $this->getDrawList();
        $next = null;
        $nextIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
        foreach ($drawList as $item)
        {
            if ($item['type'] === 0)
            {
                $next = $item;
            } else
            {
                unset($nextIds[$item['index'] - 1]);
            }
        }
        if (count($nextIds) > 1)
        {
            $nextId = $nextIds[array_rand($nextIds, 1)] ?? current($nextIds);
            $next['index'] = $nextId;
        }
        $num = random_int(1, 10000000);
        $resScale = 0;
        $drawInfo = null;// 奖品信息
        foreach ($drawList as $drawItem)
        {
            $resScale = $resScale + $drawItem['percent'] * 100000;  // 此次因为要除以100  所以直接*的时候少两个0
            if ($num <= $resScale)
            {   // 中奖了
                if (($drawItem['type'] === 4) && (new AppUserAdornInfo())->UserIsHasAdorns($uid, $drawItem['data_id']))
                {   // 已经拥有
                    $drawInfo = $next;
                    break;
                } else
                {
                    if ($drawItem['type'] === 0)
                    {
                        $drawInfo = $next;
                    } else
                    {
                        $drawInfo = $drawItem;
                    }
                    break;
                }
            }
        }

        return $drawInfo;
    }

    /**
     * 获取抽奖奖品信息
     */
    public function getDrawList()
    {
        request()->get(['page' => -1]);
        $drawList = $this->getListPage('', 'index', [], 0, 'asc', 0);
        $resData = [];
        $percent = 100;
        $id1 = 0; // 下次再来的奖品ID
        foreach ($drawList['data'] as $item)
        {
            $item = arrayKeyData2int($item, ['id', 'index', 'status', 'type', 'data_id', 'is_show_tips', 'num', 'days', 'create_time']);
            if ($item['type'] === 0)
            {
                $id1 = $item['id']; // 下次再来的奖品ID
            }
            $item['percent'] = (float)$item['percent'];
            $percent -= $item['percent'];
            $resData[$item['id']] = $item;
        }

        if ($percent > 0)
        {
            if ($id1 > 0)
            {
                $resData[$id1]['percent'] += $percent;
            }
        } elseif ($percent < 0)
        {   // 重置中奖概率  中奖概率 统一下调
            $percent = ($percent - 100) * -1;
            foreach ($resData as $id => $datum)
            {
                $resData[$id]['percent'] = $datum['percent'] * 100 / $percent;
            }
        }

        return $resData;
    }

    /**
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            $where = [];
            if ($ids)
            {
                $where['id'] = ['in', $ids];
            } else
            {
                $where['status'] = 1;
            }

            return $this->where($where)->order('index asc')->column('type,status,name,des,index,data_id,data_name,is_show_tips,img,img_size,pic,pic_size,percent,num,days,create_time', 'id');
        }
        catch (\Exception $e)
        {
            return [];
        }
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $datas = parent::batchGetInfoByIds($cids, $field);

        foreach ($datas as $id => $dataItem)
        {
            $datas[$id] = arrayKeyData2int($dataItem, ['id', 'index', 'status', 'type', 'data_id', 'num', 'days', 'create_time']);
        }

        return $datas;
    }

    /**
     * 记录领取记录
     * @param string $drawInfo
     */
    public function setDrawRecordCacheAdd(string $drawInfo): void
    {
        $len = 15;
        // 获取redis操作对象
        $redis = CacheManage::getInstance()->redisHandler;

        $cacheKey = 'lucky_draw:record:info';
        $num = $redis->lLen($cacheKey);

        if ($num >= $len)
        {
            $redis->rPop($cacheKey);
        }

        $redis->lPush($cacheKey, $drawInfo);
    }

    /**
     * 获取领取记录
     */
    public function getDrawRecordCache(): array
    {
        $redis = CacheManage::getInstance()->redisHandler;

        $giveData = $redis->lRange('lucky_draw:record:info', 0, -1);

        return $giveData ?: [];
    }

}
